package io.dshubs.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.dshubs.commons.log.SysLogOperation;
import io.dshubs.commons.security.user.SecurityUser;
import io.dshubs.dao.SysFuncDao;
import io.dshubs.dao.SysLogLoginDao;
import io.dshubs.dao.SysLogOperationDao;
import io.dshubs.entity.SysFuncEntity;
import io.dshubs.entity.SysLogLoginEntity;
import io.dshubs.entity.SysLogOperationEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.batch.BatchProperties;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tan 2021/9/2
 **/
@Slf4j
@Component
@EnableScheduling
public class SysFuncTask {

    @Autowired
    private SysLogOperationDao sysLogOperationDao;

    @Autowired
    private SysFuncDao sysFuncDao;

    @Scheduled(cron = "0 0 * * * ?")
    public void run() {
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        List<SysLogOperationEntity> creatorGroup = sysLogOperationDao.selectList(
                new QueryWrapper<SysLogOperationEntity>().ge("create_date",todayStart)
                .le("create_date",todayEnd).eq("module","archives")
                        .groupBy("creator,operation").select("creator,count(*) as count,operation")
        );

        if(CollectionUtils.isNotEmpty(creatorGroup)) {

           creatorGroup.forEach(item->{
               String operation = item.getOperation();
               log.info(item.getCreatorName() + operation);
               SysFuncEntity sysFuncEntity = new SysFuncEntity();
               sysFuncEntity.setUserId(item.getCreator());
               String[] split = operation.split(":");
               if(split.length >= 3) {
                   sysFuncEntity.setSubTitle(split[0]);
                   sysFuncEntity.setUrl(split[1]);
                   sysFuncEntity.setSrc(split[2]);
                   sysFuncEntity.setId(IdWorker.getId());
                   sysFuncEntity.setCount(item.getCount());
                   sysFuncEntity.setCreateDate(new Date());
                   sysFuncDao.delete(new QueryWrapper<SysFuncEntity>().eq("user_id",
                           item.getCreator()
                   ).eq("sub_title",sysFuncEntity.getSubTitle()));
                   sysFuncDao.insert(sysFuncEntity);
               }
           });
        }
    }
}
